package com.hhh.petadpot.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.hhh.petadopt.pojo.User;
import com.hhh.petadopt.service.TokenService;
import com.hhh.petadopt.utils.CookieUtils;
import com.hhh.petadopt.utils.E3Result;

public class AdoptIntercepter implements HandlerInterceptor {
	
	@Autowired
	private TokenService tokenService;

	

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 从cookie中取token
		String token = CookieUtils.getCookieValue(request, "token");
		//判断token是否存在
		if(StringUtils.isBlank(token)) {
			//如果不存在，未登录状态，跳转到登录页面，用户登录后跳转到当前请求的url
			String id = request.getParameter("id");
			response.sendRedirect(request.getContextPath()+"/login.html?redirect="+request.getRequestURI()+"?id="+id);
			//拦截
			return false;
			
		}
		//如果token存在，判断用户信息是否过期
		E3Result e3Result = tokenService.getUserByToken(token);
		//如果取不到,用户信息过期，需要重新登录
		if(e3Result.getStatus() != 200){
			//用户信息不存在需要重新登录，跳转到登录页面
			String id = request.getParameter("id");
			response.sendRedirect(request.getContextPath()+"/login.html?redirect="+request.getRequestURI()+"?id="+id);
			//拦截
			return false;
		}
		//取到用户信息,将数据保存到request域中
		User user = (User) e3Result.getData();
		request.setAttribute("user", user);
		return true;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		

	}

}
